<template>
  <view class="register-container">
    <view class="register-header">
          <image class="hospital-logo" src="/static/hospital-logo.png" mode="aspectFit"></image>
          <text class="hospital-name">智慧医疗健康平台</text>
          <text class="welcome-text">用户注册</text>
    </view>
    
    <view class="register-form">
		<!-- 用户名输入 -->
		  <view class="form-item">
			<image class="input-icon" src="/static/icon-user.png" mode="aspectFit"></image>
			<input class="form-input" 
				   type="text" 
				   v-model="username" 
				   @input="checkUsername"
				   placeholder="请输入用户名(2-20位)"
				   placeholder-class="input-placeholder" />
			<!-- 状态提示图标 -->
			<view class="status-icon">
			  <image v-if="usernameChecking" src="/static/icon-loading.gif" class="icon-loading"></image>
			  <image v-else-if="usernameStatus === 'exist'" src="/static/icon-error.png" class="icon-error"></image>
			  <image v-else-if="usernameStatus === 'available' && username" src="/static/icon-success.png" class="icon-success"></image>
			</view>
		  </view>
		  <!-- 用户名提示文字 -->
		  <view class="hint-box">
			<text v-if="usernameChecking" class="hint-text checking">正在检查用户名...</text>
			<text v-else-if="usernameStatus === 'exist'" class="hint-text error">该用户名已被注册</text>
			<text v-else-if="usernameStatus === 'available' && username" class="hint-text success">用户名可用</text>
			<text v-else class="hint-text default">请输入2-20位用户名</text>
		  </view>
      
			<view class="form-item">
              <image class="input-icon" src="/static/icon-phone.png" mode="aspectFit"></image>
              <input class="form-input" 
                     type="number" 
                     v-model="phone" 
                     @input="checkPhone"
                     placeholder="请输入手机号"
                     placeholder-class="input-placeholder"
                     maxlength="11" />
              <!-- 状态提示图标 -->
              <view class="status-icon">
                <image v-if="phoneChecking" src="/static/icon-loading.gif" class="icon-loading"></image>
                <image v-else-if="phoneStatus === 'exist'" src="/static/icon-error.png" class="icon-error"></image>
                <image v-else-if="phoneStatus === 'available' && phone.length===11" src="/static/icon-success.png" class="icon-success"></image>
              </view>
            </view>
            <!-- 手机号提示文字 -->
            <view class="hint-box">
              <text v-if="phoneChecking" class="hint-text checking">正在验证手机号...</text>
              <text v-else-if="phoneStatus === 'exist'" class="hint-text error">该手机号已注册</text>
              <text v-else-if="phoneStatus === 'available' && phone.length===11" class="hint-text success">手机号可用</text>
              <text v-else class="hint-text default">请输入11位手机号</text>
            </view>
      
      <view class="form-item captcha-item">
        <image class="input-icon" src="/static/icon-captcha.png" mode="aspectFit"></image>
        <input class="form-input captcha-input" 
               type="number" 
               v-model="smsCode" 
               placeholder="请输入验证码"
               placeholder-class="input-placeholder"
               maxlength="6" />
        <button class="captcha-btn" 
                :disabled="countdown > 0"
                @tap="getSmsCode">
          {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
        </button>
      </view>
      
      <view class="form-item">
        <image class="input-icon" src="/static/icon-password.png" mode="aspectFit"></image>
        <input class="form-input" 
               type="password" 
               v-model="password" 
               placeholder="请设置登录密码（6-20位）"
               placeholder-class="input-placeholder" />
      </view>
      
      <view class="form-item">
        <image class="input-icon" src="/static/icon-password.png" mode="aspectFit"></image>
        <input class="form-input" 
               type="password" 
               v-model="confirmPassword" 
               placeholder="请确认登录密码"
               placeholder-class="input-placeholder" />
      </view>
      
      <button class="register-button" 
					type="primary" 
                    @tap="handleRegister">注 册</button>
      
      <view class="login-link">
           <text>已有账号？</text>
           <text class="link-text" @tap="gotoLogin">立即登录</text>
      </view>
    </view>
  </view>
</template>

<script>
import { judgePhone, judgeAccount, getCodeTel, register, getCode } from '@/api/user.js'

export default {
  data() {
    return {
      username: '',
      phone: '',
      smsCode: '',
      password: '',
      confirmPassword: '', //确认密码
      countdown: 0,
      timer: null,
	  usernameStatus: '', //用户名的状态
	  usernameChecking: false,
	  checkTimeout: null,
	  phoneStatus: '',
	  phoneChecking: false,
	  phoneStatus: ''
    }
  },
  watch: {
    // 监听表单字段变化，计算表单是否有效
    username(val) {
      this.calculateFormValid();
    },
    phone(val) {
      this.calculateFormValid();
    },
    smsCode(val) {
      this.calculateFormValid();
    },
    password(val) {
      this.calculateFormValid();
    },
    confirmPassword(val) {
      this.calculateFormValid();
    },
    usernameStatus(val) {
      this.calculateFormValid();
    },
    phoneStatus(val) {
      this.calculateFormValid();
    }
  },
  methods: {
	  // 计算表单是否有效
    calculateFormValid() {
      this.formValid = this.usernameStatus === 'available' && 
      this.phoneStatus === 'available' && 
      this.phone.length === 11 &&
      this.smsCode.length >= 4 &&
      this.password.length >= 6 && 
      this.password === this.confirmPassword;
    },
	// 检查手机号
	checkPhone() {
	    clearTimeout(this.checkTimeout);
	      
	    // 如果手机号为空，重置状态
	    if (!this.phone) {
	      this.phoneStatus = '';
	      this.phoneChecking = false;
	      return;
	    }
	    
	    // 手机号长度不足时不检查
	    if (this.phone.length < 11) {
	      this.phoneStatus = '';
	      this.phoneChecking = false;
	      return;
	    }
	    
	    // 只有11位时才检查
	    if (this.phone.length === 11) {
	      this.phoneChecking = true;
	      this.phoneStatus = '';
	      
	      // 防抖处理，用户停止输入500ms后再请求
	      this.checkTimeout = setTimeout(async () => {
	        try {
	          const res = await judgePhone({ phone: this.phone });
	          if (res.code === 1) {
	            this.phoneStatus = res.data ? 'exist' : 'available';
	          }
	        } catch (e) {
	          /* console.error('检查手机号失败', e); */
	          this.phoneStatus = '';
	        } finally {
	          this.phoneChecking = false;
	        }
	      }, 500);
	    }
	},   
	// 检查用户名
	checkUsername() {
	    clearTimeout(this.checkTimeout);
	      
	    // 如果用户名为空，重置状态
	    if (!this.username) {
	      this.usernameStatus = '';
	      this.usernameChecking = false;
	      return;
	    }
	    
	    // 用户名长度不足时不检查
	    if (this.username.length < 2) {
	      this.usernameStatus = '';
	      this.usernameChecking = false;
	      return;
	    }
	    
	    this.usernameChecking = true;
	    this.usernameStatus = '';
	    
	    // 防抖处理，用户停止输入500ms后再请求
	    this.checkTimeout = setTimeout(async () => {
	      try {
	        const res = await judgeAccount({ account: this.username });
	        if (res.code === 1) {
	          this.usernameStatus = res.data ? 'exist' : 'available';
	        }
	      } catch (e) {
	        /* console.error('检查用户名失败', e); */
	        this.usernameStatus = '';
	      } finally {
	        this.usernameChecking = false;
	      }
	    }, 500);
	},
		
    // 获取短信验证码
	async getSmsCode() {
	  
		const res = await getCodeTel({phone: this.phone});
		console.log('验证码响应:', res);  // 调试信息
		
		// 检查响应是否为对象
		  if (res.code === 1) {
			uni.showToast({
			  title: '验证码已发送',
			  icon: 'none'
			});
			this.startCountdown();
		  } else {
			uni.showToast({
			  title: res.message || '验证码发送失败',
			  icon: 'none'
			});
		  }
	},
    
    // 倒计时
    startCountdown() {
      this.countdown = 60;
      this.timer = setInterval(() => {
        if (this.countdown <= 0) {
          clearInterval(this.timer);
          return;
        }
        this.countdown--;
      }, 1000);
    },
    
    // 注册
    async handleRegister() {
	  //验证用户名是否重复
	  if (this.usernameStatus === 'exist') {
	    uni.showToast({
	      title: '用户名已存在',
	      icon: 'none'
	    });
	    return;
	  }	
	  	    
	  if (this.usernameChecking) {
	    uni.showToast({
	      title: '正在验证用户名，请稍候',
	      icon: 'none'
	    });
	    return;
	  }
	  		
	  //验证电话号码是否重复
	  if (this.phoneChecking === 'exist') {
	  	uni.showToast({
	  		title: '电话号码已存在',
	  		icon: 'none'
	  	  });
	  	   return;
	  	  }
	  		
	  if (this.phoneChecking) {
	  	uni.showToast({
	  	  title: '正在验证电话号码，请稍候',
	  	  icon: 'none'
	  	});
	  	return;
	  }
		
      if (!this.phone || !this.smsCode || !this.password || !this.confirmPassword) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        });
        return;
      }
      
      if (this.password !== this.confirmPassword) {
        uni.showToast({
          title: '两次密码输入不一致',
          icon: 'none'
        });
        return;
      }
      
      try {
        const res = await register({
          account: this.username,
          phone: this.phone,
          code: this.smsCode,
          password: this.password,
		  surePassword: this.confirmPassword
        });
        //console.log("register",res)
		
        if (res.code === 1) {
          uni.showToast({
            title: '注册成功',
            icon: 'success'
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else if (res.code === -1) {
			uni.showToast({
			  title: res.msg,
			  icon: 'error'
			});
		} else if (res.code === -2) {
			uni.showToast({
			  title: res.msg,
			  icon: 'error'
			});
		} else if (res.code === -3) {
			uni.showToast({
			  title: res.msg,
			  icon: 'error'
			});
		} else {
			uni.showToast({
			  title: '注册失败',
			  icon: 'error'
			});
		}
      } catch (e) {
        console.error('注册失败', e);
      }
    },
    
    gotoLogin() {
      uni.navigateTo({
      	url: '/pages/login/login'
      });
    }
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
}
</script>

<style lang="scss">
.register-container {
  height: 100vh;
  background: linear-gradient(to bottom, #f0f9ff, #ffffff);
  padding: 40rpx 50rpx;
  display: flex;
  flex-direction: column;
}

.register-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
}

.hospital-logo {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.hospital-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #1a73e8;
  margin-bottom: 10rpx;
}

.welcome-text {
  font-size: 28rpx;
  color: #666;
}

.register-form {
  flex: 1;
}

.form-item {
  position: relative;
  margin-bottom: 10rpx;
  border-bottom: 1rpx solid #e0e0e0;
  padding-bottom: 10rpx;
  display: flex;
  align-items: center;
  
  &.captcha-item {
    padding-bottom: 0;
    border-bottom: none;
  }
}

.input-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 20rpx;
}

.form-input {
  flex: 1;
  height: 80rpx;
  font-size: 30rpx;
  color: #333;
  padding-right: 80rpx;
  
  &.captcha-input {
    flex: none;
    width: 300rpx;
  }
}

.input-placeholder {
  color: #bbb;
  font-size: 28rpx;
}

.captcha-btn {
  width: 200rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
  background-color: #f5f5f5;
  color: #1a73e8;
  font-size: 26rpx;
  margin-left: 20rpx;
  
  &[disabled] {
    color: #999;
    background-color: #f5f5f5;
  }
}

.status-icon {
  position: absolute;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  
  image {
    width: 100%;
    height: 100%;
  }
  
  .icon-loading {
    animation: rotating 1s linear infinite;
  }
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.hint-box {
  margin-bottom: 30rpx;
  height: 40rpx;
}

.hint-text {
  font-size: 24rpx;
  margin-left: 56rpx; /* 与输入框对齐 */
  
  &.default {
    color: #999;
  }
  
  &.checking {
    color: #1890ff;
  }
  
  &.error {
    color: #f5222d;
  }
  
  &.success {
    color: #52c41a;
  }
}

.register-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  background: linear-gradient(to right, #1a73e8, #4a90e2);
  color: #fff;
  font-size: 32rpx;
  margin-top: 40rpx;
  box-shadow: 0 10rpx 20rpx rgba(26, 115, 232, 0.2);
  
  &[disabled] {
    opacity: 0.6;
  }
}

.login-link {
  display: flex;
  justify-content: center;
  margin-top: 40rpx;
  font-size: 28rpx;
  color: #666;
}

.link-text {
  color: #1a73e8;
  margin-left: 10rpx;
}
</style>